package cn.iocoder.yudao.module.ao.service.student;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import cn.iocoder.yudao.module.ao.controller.admin.student.vo.*;
import cn.iocoder.yudao.module.ao.dal.dataobject.student.StudentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ao.dal.mysql.student.StudentMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.ao.enums.ErrorCodeConstants.*;

/**
 * 学生信息 Service 实现类
 *
 * @author 智教云枢
 */
@Service
@Validated
@Slf4j
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public Long createStudent(StudentSaveReqVO createReqVO) {
        // 插入
        StudentDO student = BeanUtils.toBean(createReqVO, StudentDO.class);
        studentMapper.insert(student);

        // 返回
        return student.getStudentId();
    }

    @Override
    public void updateStudent(StudentSaveReqVO updateReqVO) {
        // 校验存在
        validateStudentExists(updateReqVO.getStudentId());
        // 更新
        StudentDO updateObj = BeanUtils.toBean(updateReqVO, StudentDO.class);
        studentMapper.updateById(updateObj);
    }

    @Override
    public void deleteStudent(Long id) {
        // 校验存在
        validateStudentExists(id);
        // 删除
        studentMapper.deleteById(id);
    }

    @Override
        public void deleteStudentListByIds(List<Long> ids) {
        // 删除
        studentMapper.deleteByIds(ids);
        }


    private void validateStudentExists(Long id) {
        if (studentMapper.selectById(id) == null) {
            throw exception(STUDENT_NOT_EXISTS);
        }
    }

    @Override
    public StudentDO getStudent(Long id) {
        return studentMapper.selectById(id);
    }

    @Override
    public PageResult<StudentDO> getStudentPage(StudentPageReqVO pageReqVO) {
        return studentMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StudentImportRespVO importStudentList(List<StudentImportExcelVO> importStudents, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(importStudents)) {
            throw exception(STUDENT_NOT_EXISTS);
        }

        log.info("开始导入学生数据，总数量：{}，是否支持更新：{}", importStudents.size(), isUpdateSupport);

        StudentImportRespVO respVO = StudentImportRespVO.builder()
                .createStudentCount(0).updateStudentCount(0).failureStudentCount(0)
                .failureStudentNames(new ArrayList<>()).build();

        for (int i = 0; i < importStudents.size(); i++) {
            StudentImportExcelVO importStudent = importStudents.get(i);
            try {
                // 校验学生数据
                if (StrUtil.isBlank(importStudent.getName()) || StrUtil.isBlank(importStudent.getStudentNo())) {
                    String errorMsg = String.format("第%d行：姓名或学号不能为空", i + 1);
                    respVO.setFailureStudentCount(respVO.getFailureStudentCount() + 1);
                    respVO.getFailureStudentNames().add(errorMsg);
                    continue;
                }

                // 根据学号查询是否存在
                StudentDO existingStudent = studentMapper.selectByStudentNo(importStudent.getStudentNo());

                if (existingStudent != null) {
                    if (!isUpdateSupport) {
                        String errorMsg = String.format("第%d行 %s：学号已存在，且不支持更新", i + 1, importStudent.getName());
                        respVO.setFailureStudentCount(respVO.getFailureStudentCount() + 1);
                        respVO.getFailureStudentNames().add(errorMsg);
                        continue;
                    }
                    // 更新学生信息
                    updateStudentFromImport(existingStudent, importStudent);
                    studentMapper.updateById(existingStudent);
                    respVO.setUpdateStudentCount(respVO.getUpdateStudentCount() + 1);
                } else {
                    // 创建新学生
                    StudentDO newStudent = createStudentFromImport(importStudent);
                    studentMapper.insert(newStudent);
                    respVO.setCreateStudentCount(respVO.getCreateStudentCount() + 1);
                }
            } catch (Exception e) {
                String errorMsg = String.format("第%d行 %s：%s", i + 1,
                    StrUtil.isNotBlank(importStudent.getName()) ? importStudent.getName() : "未知",
                    e.getMessage());
                log.error("导入学生失败：{}", errorMsg, e);
                respVO.setFailureStudentCount(respVO.getFailureStudentCount() + 1);
                respVO.getFailureStudentNames().add(errorMsg);
            }
        }

        log.info("学生导入完成，创建：{}，更新：{}，失败：{}",
                respVO.getCreateStudentCount(), respVO.getUpdateStudentCount(), respVO.getFailureStudentCount());

        return respVO;
    }

    private StudentDO createStudentFromImport(StudentImportExcelVO importStudent) {
        StudentDO student = new StudentDO();

        // 设置姓名（限制长度）
        if (StrUtil.isNotBlank(importStudent.getName())) {
            String name = importStudent.getName().trim();
            if (name.length() > 50) {
                name = name.substring(0, 50);
            }
            student.setName(name);
        }

        // 设置学号（限制长度）
        if (StrUtil.isNotBlank(importStudent.getStudentNo())) {
            String studentNo = importStudent.getStudentNo().trim();
            if (studentNo.length() > 20) {
                studentNo = studentNo.substring(0, 20);
            }
            student.setStudentNo(studentNo);
        }

        // 设置身份证号（限制长度）
        if (StrUtil.isNotBlank(importStudent.getIdCard())) {
            String idCard = importStudent.getIdCard().trim();
            if (idCard.length() > 18) {
                idCard = idCard.substring(0, 18);
            }
            student.setIdCard(idCard);
        }

        // 性别转换（添加默认值）
        if (StrUtil.isNotBlank(importStudent.getGenderStr())) {
            String genderStr = importStudent.getGenderStr().trim();
            if ("男".equals(genderStr)) {
                student.setGender(1);
            } else if ("女".equals(genderStr)) {
                student.setGender(2);
            } else {
                // 无法识别的性别，设置默认值为1（男）
                student.setGender(1);
            }
        } else {
            // 性别为空，设置默认值为1（男）
            student.setGender(1);
        }

        // 设置其他字段（添加长度限制）
        if (StrUtil.isNotBlank(importStudent.getStudentPhone())) {
            String phone = importStudent.getStudentPhone().trim();
            // 限制电话号码长度为20个字符
            if (phone.length() > 20) {
                phone = phone.substring(0, 20);
            }
            student.setPhone(phone);
        }
        if (StrUtil.isNotBlank(importStudent.getGuardianPhone())) {
            String guardianPhone = importStudent.getGuardianPhone().trim();
            // 限制家长电话号码长度为20个字符
            if (guardianPhone.length() > 20) {
                guardianPhone = guardianPhone.substring(0, 20);
            }
            student.setGuardianPhone(guardianPhone);
        }

        // 设置状态（从Excel读取或默认值）
        if (StrUtil.isNotBlank(importStudent.getStatus())) {
            String statusStr = importStudent.getStatus().trim();
            // 根据Excel中的状态文本转换为数字
            Integer statusValue = convertStatusToNumber(statusStr);
            student.setStatus(statusValue);
        } else {
            student.setStatus(0); // 默认在读状态
        }

        // 设置必填字段的默认值
        student.setClassId(1L); // 设置默认班级ID，您可以根据实际需要调整
        student.setMajorId(1L); // 设置默认专业ID，您可以根据实际需要调整
        student.setEnrollmentDate(LocalDate.now()); // 设置默认入学日期为当前日期
        student.setEnrollmentTermId(1L); // 设置默认入学学期ID

        return student;
    }

    /**
     * 将状态文本转换为数字
     */
    private Integer convertStatusToNumber(String statusStr) {
        if (StrUtil.isBlank(statusStr)) {
            return 0; // 默认在读
        }

        statusStr = statusStr.trim();

        // 如果已经是数字，直接转换
        if (statusStr.matches("\\d+")) {
            int status = Integer.parseInt(statusStr);
            return (status >= 0 && status <= 4) ? status : 0;
        }

        // 根据中文状态转换
        switch (statusStr) {
            case "在读":
            case "在校":
            case "正常":
                return 0;
            case "毕业":
            case "已毕业":
                return 1;
            case "退学":
            case "已退学":
                return 2;
            case "休学":
            case "暂停学习":
                return 3;
            case "转学":
            case "已转学":
                return 4;
            default:
                return 0; // 默认在读
        }
    }

    private void updateStudentFromImport(StudentDO existingStudent, StudentImportExcelVO importStudent) {
        // 更新姓名（限制长度）
        if (StrUtil.isNotBlank(importStudent.getName())) {
            String name = importStudent.getName().trim();
            if (name.length() > 50) {
                name = name.substring(0, 50);
            }
            existingStudent.setName(name);
        }

        // 更新身份证号（限制长度）
        if (StrUtil.isNotBlank(importStudent.getIdCard())) {
            String idCard = importStudent.getIdCard().trim();
            if (idCard.length() > 18) {
                idCard = idCard.substring(0, 18);
            }
            existingStudent.setIdCard(idCard);
        }

        // 性别转换（添加默认值）
        if (StrUtil.isNotBlank(importStudent.getGenderStr())) {
            String genderStr = importStudent.getGenderStr().trim();
            if ("男".equals(genderStr)) {
                existingStudent.setGender(1);
            } else if ("女".equals(genderStr)) {
                existingStudent.setGender(2);
            } else {
                // 无法识别的性别，设置默认值为1（男）
                existingStudent.setGender(1);
            }
        } else {
            // 性别为空，确保有默认值
            if (existingStudent.getGender() == null) {
                existingStudent.setGender(1);
            }
        }

        // 更新其他字段（添加长度限制）
        if (StrUtil.isNotBlank(importStudent.getStudentPhone())) {
            String phone = importStudent.getStudentPhone().trim();
            if (phone.length() > 20) {
                phone = phone.substring(0, 20);
            }
            existingStudent.setPhone(phone);
        }
        if (StrUtil.isNotBlank(importStudent.getGuardianPhone())) {
            String guardianPhone = importStudent.getGuardianPhone().trim();
            if (guardianPhone.length() > 20) {
                guardianPhone = guardianPhone.substring(0, 20);
            }
            existingStudent.setGuardianPhone(guardianPhone);
        }

        // 更新状态（从Excel读取）
        if (StrUtil.isNotBlank(importStudent.getStatus())) {
            String statusStr = importStudent.getStatus().trim();
            Integer statusValue = convertStatusToNumber(statusStr);
            existingStudent.setStatus(statusValue);
        }

        // 确保必填字段有值
        if (existingStudent.getClassId() == null) {
            existingStudent.setClassId(1L);
        }
        if (existingStudent.getMajorId() == null) {
            existingStudent.setMajorId(1L);
        }
        if (existingStudent.getEnrollmentDate() == null) {
            existingStudent.setEnrollmentDate(LocalDate.now());
        }
        if (existingStudent.getEnrollmentTermId() == null) {
            existingStudent.setEnrollmentTermId(1L);
        }
    }

}